package com.lizk.study.netty.day006;

import com.lizk.study.netty.entity.ClientContent;
import com.lizk.study.netty.utils.NettyUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

/**
 * @author lizhikui
 * @date 2019/6/22 9:20
 */
public class ProtobufClient {
    public static void main(String[] args) {
        ClientContent clientContent = NettyUtils.createClientContent(NioSocketChannel.class);
        clientContent.getBootstrap().handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
                        .addLast(new ProtobufVarint32FrameDecoder())
                        .addLast(new ProtobufDecoder(User.Person.getDefaultInstance()))
                        .addLast(new ProtobufVarint32LengthFieldPrepender())
                        .addLast(new ProtobufEncoder())
                        .addLast(new SimpleChannelInboundHandler<User.Person>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, User.Person msg) throws Exception {
                                System.out.println(msg.toString());
                            }

                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                User.Person p = User.Person.newBuilder()
                                        .setAge(16)
                                        .setSex(true)
                                        .setName("李志奎")
                                        .setEmail("lzkmm@sina.com")
                                        .build();
                                ctx.writeAndFlush(p);
                            }

                            @Override
                            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                ctx.close();
                            }
                        });

            }
        });

        try {
            NettyUtils.conn(clientContent,"localhost",9999);
        } catch (InterruptedException e) {
            NettyUtils.stop(clientContent);
            e.printStackTrace();
        }
    }
}
